package com.jxau.service.impl;

import com.jxau.entity.User;
import com.jxau.entity.UserSession;
import com.jxau.entity.view.FollowerAndFansNum;
import com.jxau.entity.view.Liker;
import com.jxau.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jxau.service.UserService;
import com.jxau.util.Constant;
import com.jxau.util.FileUtil;
import com.jxau.util.HtmlUtil;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据账号和密码在数据库查询是否有此记录
     *
     * @param id
     * @param password
     * @return
     */
    @Override
    public User login(String id, String password) {
        User user = userMapper.existsUser(id, password);
        return user;
    }

    @Override
    public List<User> show() {
        return userMapper.getAllUsers();
    }

    @Override
    public User findUserById(String id) {

        //按编号查询用户
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public List<User> findUserByName(String name) {

        //按名字查找用户
        List<User> users = userMapper.findUserByName(name);
        return users;
    }

    @Override
    public int updateUser(User user) {

        int result = userMapper.updateUser(user);
        return result;
    }

    @Override
    public int deleteUser(String id) {
        int result = userMapper.deleteByPrimaryKey(id);
        return result;
    }

    @Override
    public List<User> getPages(int pageNum, int pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.getAllUsers();
        return users;
    }

    @Override
    public PageInfo<User> getPagesData() {

        List<User> users = userMapper.getAllUsers();
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo;
    }

    @Override
    public int addUser(User user) {

        return userMapper.addUser(user);
    }

    public Integer login(String id, String password, HttpSession session) {
        Integer role = userMapper.queryByIdAndPwd(id, password);
        if (role == null) {
            //登录失败
            return null;
        } else {
            //登录成功
            UserSession userSession = new UserSession(id, role);
            //将user基础信息id、role存入session中
            session.setAttribute("user", userSession);
            //返回权限标识方便前端根据根据权限标识跳转至不同首页
            return role;
        }
    }

    @Override
    public String queryHeadPhotoById(String id) {
        return userMapper.queryHeadPhotoById(id);
    }

    @Override
    public void doUnLike(Integer articleId, String uid) {
        userMapper.doUnLike(articleId, uid);
    }

    @Override
    public void doLike(Integer articleId, String uid) {
        userMapper.doLike(articleId, uid);
    }

    @Override
    public void doCollect(Integer articleId, String uid) {
        userMapper.doCollect(articleId, uid);
    }

    @Override
    public void doUnCollect(Integer articleId, String uid) {
        userMapper.doUnCollect(articleId, uid);
    }

    @Override
    public User queryUserById(String uid) {
        return userMapper.queryUserById(uid);
    }

    @Override
    public void doUnLikeForComment(Integer commentId, String uid) {
        userMapper.doUnLikeForComment(commentId, uid);
    }

    @Override
    public void doLikeForComment(Integer commentId, String uid) {
        userMapper.doLikeForComment(commentId, uid);
    }

    @Override
    public User queryUserInfoById(String uid) {
        User user = userMapper.queryUserInfoById(uid);
        user.setPassword(null);
        return user;
    }

    @Override
    public void updateHeadPhoto(String uid, MultipartFile mPFile) {
        //把上传的头像图片存入服务器
        //依据时间戳改文件名
        String originFileName = mPFile.getOriginalFilename();
        String fileTail = FileUtil.getFileTail(originFileName);
        Date now = new Date();
        String newFileName = now.getTime() + "." + fileTail;
        //上传文件
        String realPath = FileUtil.HEAD_PHOTO_PATH + newFileName;
        File file = new File(realPath);
        if (!file.exists()) {
            //该文件不存在
            try {
                //写入流
                mPFile.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //改数据库中对应user的head_photo字段
        //查询原来的头像的文件名
        String oldFileName = userMapper.selectHeadPhoto(uid);
        userMapper.updateHeadPhoto(uid, newFileName);
        //3、删除原来的头像(若不是默认头像则删除，否则不删除)
        if (!"default.jpeg".equals(oldFileName)) {
            //非默认头像，删除
            String oldFilePath = FileUtil.HEAD_PHOTO_PATH + oldFileName;
            File oldFile = new File(oldFilePath);
            oldFile.delete();
        }
    }

    @Override
    public void updateUserInfo(User user) {
        userMapper.updateUserInfo(user);
    }

    @Override
    public ArrayList<User> queryFollowers(String uid) {
        return userMapper.queryFollowers(uid);
    }

    @Override
    public FollowerAndFansNum queryFollowerAndFansNum(String uid) {
        return userMapper.queryFollowerAndFansNum(uid);
    }

    @Override
    public Boolean queryIsFollow(String uid, String otherUid) {
        int resultNum = userMapper.queryIsFollow(uid, otherUid);
        if (resultNum == 0)
            return false;
        else
            return true;
    }

    @Override
    public void followUser(String uid, String otherUid) {
        // 防止二次关注bug
        int resultNum = userMapper.queryIsFollow(uid, otherUid);
        if(resultNum == 0){
            userMapper.followUser(uid, otherUid);
        }
    }

    @Override
    public void cancelFollow(String uid, String otherUid) {
        userMapper.cancelFollow(uid, otherUid);
    }

    @Override
    public Boolean register(String uid, String password, HttpSession session) {
        // 查询账号是否已被注册
        int isExist = userMapper.queryUserIsExistByUid(uid);
        if (isExist == 0) {
            // 账号未被注册
            // 注册操作
            userMapper.insertUser(uid, password);
            // 登录操作
            UserSession userSession = new UserSession(uid, 0);
            session.setAttribute("user", userSession);
            return true;
        } else {
            // 账号已被注册
            return false;
        }
    }
    @Override
    public Map<String, Integer> getNewCommentAndLikeNum(String uid) {
        Integer newCommentNum = userMapper.findNewCommentNum(uid);
        Integer newArticleLikeNum = userMapper.findNewArticleLikeNum(uid);
        Integer newCommentLikeNum = userMapper.findNewCommentLikeNum(uid);
        Integer newLikeNum = newArticleLikeNum + newCommentLikeNum;
        Map<String, Integer> result = new HashMap<>();
        result.put("newCommentNum", newCommentNum);
        result.put("newLikeNum", newLikeNum);
        return result;
    }

    @Override
    public Map<String, Object> getNewLiker(String uid, int nowPage) {
        List<Liker> likerList = userMapper.getNewLikerOfArticle(uid);
        List<Liker> commentLikerList = userMapper.getNewLikerOfComment(uid);
        likerList.addAll(commentLikerList);
        for (int i = 0; i < likerList.size(); i++) {
            likerList.get(i).setTitle(HtmlUtil.parseString(likerList.get(i).getTitle(), 60));
            likerList.get(i).setComment(likerList.get(i).getComment()==null?null:HtmlUtil.parseString(likerList.get(i).getComment(), 60));
            // 根据时间倒序排序
            for (int j = i + 1; j < likerList.size(); j++) {
                if (likerList.get(j).getDate().after(likerList.get(i).getDate())) {
                    Collections.swap(likerList, i, j);
                }
            }
        }
        Map<String,Object> map= new HashMap<>();
        map.put("pageNum",likerList.size()!=0?(likerList.size()/Constant.LIKE_ABORT_ME_PAGE_SIZE+1):0);
        List<Liker> subLikeList = likerList.subList((nowPage - 1)*Constant.LIKE_ABORT_ME_PAGE_SIZE,
                Math.min(likerList.size(), nowPage * Constant.LIKE_ABORT_ME_PAGE_SIZE));
        map.put("likerList",subLikeList);
        return map;
    }

    @Override
    public void cleanRedPointOfLike(String uid) {
        userMapper.updateReadFlagOfLikeArticle(uid);
        userMapper.updateReadFlagOfLikeComment(uid);
    }

    @Override
    public ArrayList<User> queryFans(String uid) {
        return userMapper.queryFans(uid);
    }
}
